package com.seeyon.apps.gkcwplugin.util;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;

import com.alibaba.fastjson.JSONObject;
public class HttpKit {
	private static PoolingHttpClientConnectionManager cm;
	private static String EMPTY_STR = "";

	private static void init() {
		if (cm == null) {
			cm = new PoolingHttpClientConnectionManager();
			cm.setMaxTotal(50);// 整个连接池最大连接数
			cm.setDefaultMaxPerRoute(5);// 每路由最大连接数，默认值是2
		}
	}

	public static void main(String[] args) {
		
//		dept();
		//member();
		//试用转正单
        zhuanzheng();
		
	}
	private static void zhuanzheng() {
		// TODO 自动生成的方法存根
		String url = "http://172.16.234.33:8085/api/HR/EmployeeProbationEnd";
		try {
			String json = "{\"EmpCode\": \"Li0059\", \"ProbationTestScore\": \"80\",\"ProbationCompleteDate\": "
					+ "\"2022-09-30\",\"EffectDate\": \"2022-08-30\",\"CustomJson\": \"\"";
			String res = postByHeader(url,json,"AAAAC","47D9467BY6FE546BAO059B7793Q21001A08Q");
			System.out.println(res);
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
	}

	/**
	 * 通过连接池获取HttpClient
	 */
	private static void  dept() {
		String url = "http://172.16.234.33:8085/api/HR/GetOrganizationalList?modifyTime=2011-08-10";
//		String url = "http://172.16.234.33:8085/api/HR/GetEmpListByModifyDateOrEmpCode?modifyDate=&empCode=&isPersonReport=true";
//		CustomerCode:AAAAC 
//		AccessToken:47D9467BY6FE546BAO059B7793Q21001A08Q
		try {
			String res = httpsGet(url,"AAAAC","47D9467BY6FE546BAO059B7793Q21001A08Q");
			System.out.println(res);
			JSONObject jsonObject = JsonKit.parse(res);
			String result = (String) jsonObject.get("Result");
			System.out.println("result.size===="+result);
			JSONArray jsonArray = new JSONArray(result);
			System.out.println("jsonArray.size===="+jsonArray.length());
			for (int i = 0; i < jsonArray.length(); i++) {
				//System.out.println("jsonArray.get(i)===="+jsonArray.get(i));
				org.json.JSONObject obj = (org.json.JSONObject) jsonArray.get(i); 
//				System.out.println("result====2222");
				String deptName = (String) obj.get("OrganizationalName");
				String deptCode = (String) obj.get("OrganizationalID");
				String parentId = (String) obj.get("ParentOrganizationalID");
				boolean isDisable = (boolean) obj.get("IsDisable");//0为不禁用，1为禁用
				String orgType = (String) obj.get("OrgType");//0为不禁用，1为禁用
				System.out.println("deptName="+deptName+",deptCode====="+deptCode+",parentId====="+parentId+",isDisable====="+isDisable+",orgType====="+orgType);
				
			}
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
	}
	
	/**
	 * 人员信息
	 */
	private static void  member() {
//		String url = "http://172.16.234.33:8085/api/HR/GetOrganizationalList?modifyTime=2011-08-10";
		String url = "http://172.16.234.33:8085/api/HR/GetEmpListByModifyDateOrEmpCode?modifyDate=&empCode=&isPersonReport=true";
//		CustomerCode:AAAAC 
//		AccessToken:47D9467BY6FE546BAO059B7793Q21001A08Q
		try {
			String res = httpsGet(url,"AAAAC","47D9467BY6FE546BAO059B7793Q21001A08Q");
			System.out.println(res);
			JSONObject jsonObject = JsonKit.parse(res);
//			System.out.println(obj); 
			
		//	ArrayList result = (ArrayList) jsonObject.get("Result");
//			LinkedHashMap result = (LinkedHashMap) jsonObject.get("Result");
			String result = (String) jsonObject.get("Result");
			System.out.println("result.size===="+result);
			JSONArray jsonArray = new JSONArray(result);
			System.out.println("jsonArray.size===="+jsonArray.length());
			for (int i = 0; i < jsonArray.length(); i++) {
				//System.out.println("jsonArray.get(i)===="+jsonArray.get(i));
				org.json.JSONObject obj = (org.json.JSONObject) jsonArray.get(i); 
//				System.out.println("result====2222");
				String cNName = (String) obj.get("CNName");
				String empCode = (String) obj.get("EmpCode");
				String gender = (String) obj.get("Gender");
				String Birthday = (String) obj.get("Birthday");//0为不禁用，1为禁用
				String PositionName = (String) obj.get("PositionName");//0为不禁用，1为禁用
				String OrganizationalID = (String) obj.get("OrganizationalID");//0为不禁用，1为禁用
				String MobileNumber = (String) obj.get("MobileNumber");//0为不禁用，1为禁用
				String Email = (String) obj.get("Email");//0为不禁用，1为禁用
				String JoinDate = (String) obj.get("JoinDate");
				String CN_Rank = (String) obj.get("CN_Rank");
				
				System.out.println("cNName="+cNName+",empCode="+empCode+",gender="+gender+",Birthday="+Birthday+",PositionName="+PositionName+",CN_Rank="+CN_Rank+",OrganizationalID="+OrganizationalID+",JoinDate="+JoinDate);
				
			}
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 通过连接池获取HttpClient
	 */
	private static CloseableHttpClient getHttpClient() {
		init();
		return HttpClients.custom().setConnectionManager(cm).build();
	}

	public static String get(String url) throws Exception {
		HttpGet httpGet = new HttpGet(url);
		return getResult(httpGet);
	}

	public static String httpsGet(String url,String CustomerCode,String AccessToken) throws Exception {
		HttpGet httpGet = new HttpGet(url);
		httpGet.setHeader("CustomerCode", CustomerCode);
		httpGet.setHeader("AccessToken",AccessToken);
		return getResult(httpGet);
	}
	
	
	public static String get(String url, Map<String, Object> params) throws Exception {
		URIBuilder ub = new URIBuilder();
		ub.setPath(url);

		ArrayList<NameValuePair> pairs = covertParams2NVPS(params);
		ub.setParameters(pairs);

		HttpGet httpGet = new HttpGet(ub.build());
		return getResult(httpGet);
	}

	public static String get(String url, Map<String, Object> headers, Map<String, Object> params) throws Exception {
		URIBuilder ub = new URIBuilder();
		ub.setPath(url);

		ArrayList<NameValuePair> pairs = covertParams2NVPS(params);
		ub.setParameters(pairs);

		HttpGet httpGet = new HttpGet(ub.build());
		for (Map.Entry<String, Object> param : headers.entrySet()) {
			httpGet.addHeader(param.getKey(), String.valueOf(param.getValue()));
		}
		return getResult(httpGet);
	}

	public static String post(String url) throws Exception {
		HttpPost httpPost = new HttpPost(url);
		httpPost.setHeader("Authorization", "Basic b2E6Y3VtamFwZWY=");
		return getResult(httpPost);
	}

	public static String httpPost(String url,String CustomerCode,String AccessToken) throws Exception {
		HttpPost httpPost = new HttpPost(url);
		httpPost.setHeader("CustomerCode", CustomerCode);
		httpPost.setHeader("AccessToken",AccessToken);
		return getResult(httpPost);
	}
	
	
	public static String post(String url, Map<String, Object> params) throws Exception {
		HttpPost httpPost = new HttpPost(url);
		ArrayList<NameValuePair> pairs = covertParams2NVPS(params);
		httpPost.setEntity(new UrlEncodedFormEntity(pairs, "UTF-8"));
		return getResult(httpPost);
	}
	
	public static String httpsPost(String url, Map<String, Object> params) throws Exception {
		HttpPost httpPost = new HttpPost(url);
		ArrayList<NameValuePair> pairs = covertParams2NVPS(params);
		httpPost.setEntity(new UrlEncodedFormEntity(pairs, "UTF-8"));
		return getResult(httpPost);
	}
	
	
	
	
	public static String post(String url, String json) throws Exception {
		HttpPost httpPost = new HttpPost(url);
		StringEntity entity = new StringEntity(json, "UTF-8");
		entity.setContentType("application/json");
		httpPost.setEntity(entity);
		return getResult(httpPost);

	}
	
	public static String postByHeader(String url, String json,String CustomerCode,String AccessToken) throws Exception {
		HttpPost httpPost = new HttpPost(url);
		StringEntity entity = new StringEntity(json, "UTF-8");
		entity.setContentType("application/json");
		httpPost.setHeader("CustomerCode", CustomerCode);
		httpPost.setHeader("AccessToken",AccessToken);
		httpPost.setEntity(entity); 
		return getResult(httpPost);

	}

	public static String post(String url, Map<String, Object> headers, Map<String, Object> params) throws Exception {
		HttpPost httpPost = new HttpPost(url);

		for (Map.Entry<String, Object> param : headers.entrySet()) {
			httpPost.addHeader(param.getKey(), String.valueOf(param.getValue()));
		}

		ArrayList<NameValuePair> pairs = covertParams2NVPS(params);
		httpPost.setEntity(new UrlEncodedFormEntity(pairs, "UTF_8"));

		return getResult(httpPost);
	}

	private static ArrayList<NameValuePair> covertParams2NVPS(Map<String, Object> params) {
		ArrayList<NameValuePair> pairs = new ArrayList<NameValuePair>();
		for (Map.Entry<String, Object> param : params.entrySet()) {
			pairs.add(new BasicNameValuePair(param.getKey(), String
					.valueOf(param.getValue())));
		}

		return pairs;
	}

	/**
	 * 处理Http请求
	 * 
	 * @param request
	 * @return
	 */
	private static String getResult(HttpRequestBase request) throws Exception{
		// CloseableHttpClient httpClient = HttpClients.createDefault();
		CloseableHttpClient httpClient = getHttpClient();
		CloseableHttpResponse response = httpClient.execute(request);
		// response.getStatusLine().getStatusCode();
		HttpEntity entity = response.getEntity();
		if (entity != null) {
			// long len = entity.getContentLength();// -1 表示长度未知
			String result = EntityUtils.toString(entity);
			response.close();
			// httpClient.close();
			return result;
		}
		return EMPTY_STR;
	}
	
}
